<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="./images/chang.ico">
    <link rel="stylesheet" href="./css/normalize.css">
    <link rel="stylesheet" href="./css/common.css">
    <link rel="stylesheet" href="./css/talkRoom.css">
    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
        integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!-- 字体图标 -->
    <link rel="stylesheet" href="./css/font-awesome.min.css">
    <!-- 点击爱心 -->
    <script src="./js/love.js"></script>
    <title>聊天室</title>
</head>

<body>
    <!-- 头部 -->
    <header>
        <nav class="navbar navbar-inverse">
            <div class="container-fluid">
                <!-- Brand and toggle get grouped for better mobile display -->
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                        data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="./index.html">首页</a>
                </div>

                <!-- Collect the nav links, forms, and other content for toggling -->
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul class="nav navbar-nav">
                        <li><a href="./photos.html?id=1">相册</a></li>
                        <li><a href="./video.html">视频</a></li>
                        <li><a href="./game.html">游戏</a></li>
                    </ul>
                    <form class="navbar-form navbar-left">
                        <div class="form-group">
                            <input type="text" class="form-control searchInput" placeholder="Search">
                        </div>
                        <button type="button" class="btn btn-default" onclick="search()">搜索</button>
                    </form>
                    <!-- 文件上传 -->
                    <form id="uploadForm" class="navbar-form navbar-left">
                        <input type="file" name="fileUpload" id="fileUpload">
                    </form>
                    <ul class="nav navbar-nav navbar-right">
                        <li><a href="./talkRoom.html">聊天室</a></li>
                        <li><a href="./dreamTree.html">许愿树</a></li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
                                aria-haspopup="true" aria-expanded="false">当前在线人数:<span class="userNum">0</span><span
                                    class="caret"></span></a>
                            <ul class="dropdown-menu userList">
                                <!-- <li><a href="#">用户1</a></li> -->
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="talk">
        <!-- <div id="camera">
            <div id="whoCamera">
                <video src="http://121.37.209.61:8080/upload/video/stay-b.mp4"
                    style="width: 100%;height: 100%;"></video>
            </div>
            <div id="myCamera">
                <video src="http://121.37.209.61:8080/upload/video/stay-b.mp4"
                    style="width: 100%;height: 100%;"></video>
            </div>
        </div> -->
        <div class="content-wrap">

            <!-- 消息内容 -->
            <!-- <div class="item">
                <span class='username'>username</span>
                <div class="content">你好</div>
                <span>2022-08-02 10:01</span>
            </div> -->
            <!-- 系统消息 -->
            <!-- <div class="item" style="align-items: center;">
                <span class="sysTip" >系统提示：张伟加入聊天室</span>
            </div> -->
        </div>
        <form id="form">
            <div class="plugs col-md-12 col-xs-12">
                <i class="fa fa-file-o" onclick="clickFile()"></i>
            </div>
            <textarea name="textarea" id="textarea" cols="30" rows="10" placeholder="请在此输入"></textarea>
            <button id="submit" type="submit">发送</button>
        </form>
    </div>


    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="./js/timeUtil.js"></script>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
        integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
        crossorigin="anonymous"></script>
    <script src="./js/globalSearch.js"></script>
    <script>
        let nickName = prompt('输入你的昵称')
        sessionStorage.setItem('nickName', nickName)
        let socket = new WebSocket('ws://121.37.209.61:8000')

        //接受消息
        socket.onmessage = function (res) {
            let item = JSON.parse(res.data)
            switch (item.type) {
                //判断socketKEY
                case 'key':
                    console.log(item);
                    sessionStorage.setItem('socketKey', item.data)
                    //新用户加入
                    let talkTime = formatDate(new Date())
                    let newUser = {
                        type: 'center',
                        username: nickName,
                        talkTime,
                        key: item.data
                    }
                    socket.send(JSON.stringify(newUser))
                    break
                //判断在线用户信息
                case 'userInfo':
                    sessionStorage.setItem('userNum', item.userNum)
                    sessionStorage.setItem('userList', JSON.stringify(item.userList))
                    $('.userNum').html(item.userNum)
                    let userListEle = item.userList.map(uitem => {
                        return `<li><a href="#" data-key='${uitem.key}'>${uitem.username}</a></li>`
                    }).join('')
                    $('.userList').html(userListEle)
                    break
                default:
                    //推入数组
                    contentList.push(item)
                    loadContent(contentList)
                    // 自动保持底部
                    keepBottom()
            }
        }
    </script>
    <script>
        //初始化
        let contentList = [
            // {
            //     type: 'left',
            //     username: '小明',
            //     content: '你好',
            //     talkTime: '2022-08-02 10:01'
            // },
            // {
            //     type: 'right',
            //     username: '小红',
            //     content: '你好',
            //     talkTime: '2022-08-02 10:01'
            // },
            // {
            //     type: 'center',
            //     username: '蔡徐坤',
            //     content: '',
            //     talkTime: '2022-08-02 10:01'
            // }
        ]
        //加载聊天内容
        loadContent(contentList)
        // 自动保持底部
        keepBottom()
        //发送消息
        function sendMsg() {
            $('#form').on('submit', function (e) {
                e.preventDefault()
                let content = $('#textarea').val()
                //内容为空不发送
                if (!content) {
                    return
                }
                let talkTime = formatDate(new Date())
                let key = sessionStorage.getItem('socketKey')
                let item = {
                    type: 'right',
                    username: sessionStorage.getItem('nickName'),
                    content,
                    talkTime,
                    key,
                }
                socket.send(JSON.stringify(item))
                //重置输入框，获取焦点
                $('#textarea').val('')
                $('#textarea').focus()
            })
        }
        sendMsg()
        //加载对话内容
        function loadContent(list) {
            console.log('当前对话内容', contentList);
            let listEle = list.map(item => {
                if (item.type == 'center') {
                    return `<div class="item" style="align-items: center;">
                                <span class="sysTip">系统提示：${item.username} ${item.logout ? '离开' : '加入'}聊天室</span>
                            </div>`
                } else {
                    return ` <div class="item" style='${item.type == 'left' ? 'align-items: flex-start;' : 'align-items: flex-end;'}'>
                                <span class='username'>${item.username}</span>
                                <div class="content">${item.content}</div>
                                <span>${item.talkTime}</span>
                            </div>`
                }
            }).join('')
            $('.content-wrap').html(listEle)
        }
        //选择用户
        function chooseUser() {
            $('.userList').on('click', 'li', function (e) {
                console.log(e.target);
            })
        }
        chooseUser()
        // 自动保持底部
        function keepBottom() {
            let scHight = $('.content-wrap')[0].scrollHeight - $('.content-wrap')[0].clientHeight
            $('.content-wrap').scrollTop(scHight)
        }
        //点击上传文件图标
        function clickFile() {
            $('#fileUpload').click()
        }
        // 文件上传处理
        function uploadFile() {
            $('#fileUpload').on('change', function () {
                let file = this.files[0]
                let formData = new FormData()
                formData.append('file', file)
                console.log(formData.get('file'));
                $.ajax({
                    url: 'http://121.37.209.61:3000/upload/file',
                    type: 'post',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: (res) => {
                        console.log(res);
                        let talkTime = formatDate(new Date())
                        let fileData = {
                            type: 'file',
                            username: sessionStorage.getItem('nickName'),
                            filename: res.data.filename,
                            url: res.data.url,
                            key: sessionStorage.getItem('socketKey'),
                            talkTime,
                        }
                        socket.send(JSON.stringify(fileData))
                        //清空表单
                        let dt = new DataTransfer()
                        this.files = dt.files
                    },
                    fail: (err) => {
                        console.log(err);
                        //清空表单
                        let dt = new DataTransfer()
                        this.files = dt.files
                    }
                })
            })
        }
        uploadFile()

        //检测摄像头权限
        // function getCamera() {
        //     window.addEventListener('DOMContentLoaded', function () {
        //         if (navigator.mediaDevices == undefined) {
        //             alert('未检测到可用的设备！')
        //             return
        //         }
        //         navigator.getUserMedia = navigator.getUserMedia ||
        //             navigator.webkitGetUserMedia ||
        //             navigator.mozGetUserMedia
        //         if (navigator.getUserMedia) {
        //             navigator.getUserMedia({
        //                 audio: true,
        //                 video: true
        //             },
        //                 function (stream) {
        //                     console.log('同意开启，关闭摄像头占用')
        //                     //播放流可以通过document.getElementById('#video').srcObject=stream  播放
        //                     //----------------------------------这里写同意摄像头以后需要做的业务逻辑-----------------------

        
        //                     //这是关闭流的方法----------------start
        //                     let tracks = stream.getTracks();
        //                     for (var i = 0; i < tracks.length; i++) {
        //                         tracks[i].stop();
        //                     }
        //                     //这是关闭流的方法----------------end

        //                 },
        //                 function (err) {
        //                     alert('请在浏览器设置中允许访问麦克风和摄像头！')
        //                 }
        //             )
        //         } else {
        //             alert('您的设备暂不支持媒体采集！')
        //         }
        //     }, false)
        // }
        // getCamera()
    </script>

</body>

</html>